package com.example.demo.annotation;


import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author ghl
 * @version 1.0
 * @date 2022/9/21 10:17
 * @description 测试实体
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD})
@Constraint(validatedBy = ColumnLengthValid.ColumnLengthValidator.class)
@Inherited
public @interface ColumnLengthValid {

    int maxLength() default 0;

    String message() default "字段超长！";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    class ColumnLengthValidator implements ConstraintValidator<ColumnLengthValid, Object> {

        private int maxLength;

        @Override
        public void initialize(ColumnLengthValid constraintAnnotation) {
            maxLength = constraintAnnotation.maxLength();
        }

        @Override
        public boolean isValid(Object obj, ConstraintValidatorContext constraintValidatorContext) {
            return obj == null || obj.toString().length() <= maxLength;
        }

    }

}
